package config

import (
	"fmt"
	"github.com/chicken-team-outside/chicken_transmission/client_core/service"
	"github.com/chicken-team-outside/chicken_transmission/logger"
	"go.uber.org/zap"
	"go.uber.org/zap/zapcore"
	"strings"
)

func applyLogLevel(level string) error {
	l := zapcore.InfoLevel
	err := l.UnmarshalText([]byte(level))
	if err != nil {
		return err
	}
	logger.SetLogLevel(l)
	return nil
}

func LogLevel() string {
	return strings.ToUpper(zap.L().Level().String())
}

func SaveLogLevel(level string) error {
	err := applyLogLevel(level)
	if err == nil {
		err = service.SaveConfigData([]byte("logger_level"), level)
	}
	return err
}

func initLogLevel() error {
	cfg := strings.ToUpper(zap.L().Level().String())
	err := service.GetOrSaveConfig([]byte("logger_level"), &cfg)
	if err != nil {
		return fmt.Errorf("failed to get logger_level: %w", err)
	}
	err = applyLogLevel(cfg)
	if err != nil {
		return fmt.Errorf("failed to apply logger_level: %w", err)
	}
	return nil
}
